package com.tanhua.commons.templates;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.tanhua.commons.properties.OssProperties;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class OssTemplate {

    private OssProperties properties;

    public OssTemplate(OssProperties properties){
        this.properties = properties;
    }

    /**
     * 上传文件到阿里云OSS
     * @param fileName 上传文件名
     * @param inputStream 文件输入流
     * @return 图片访问地址
     */
   public String upload(String fileName, InputStream inputStream){
        //Endpoint以杭州为例，其他Region请按实际情况填写
       String endpoint = properties.getEndpoint();
       //阿里云主张好AccessKey拥有所有API的访问权限
       String accessKey = properties.getAccessKey();
       String secret = properties.getSecret();
       //创建OSSClient实例
       OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secret);
       //获取上传后缀名
       String sufix = fileName.substring(fileName.lastIndexOf("."));
       /**
        * 文件名称
        *   images/2021/03/01/uuid(格式)
        *   拼接图片名称如下：
        */
       String name = "images/"
               + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
               +"/"
               + UUID.randomUUID().toString()
               +sufix;
       ossClient.putObject(properties.getBucketName(),name,inputStream);
       ossClient.shutdown();

       return properties.getUrl() + "/" + name;
   }
}
